﻿Imports DAL
Imports System.Linq
Imports System.Globalization
Imports System.Threading
Imports System.Drawing.Printing
Imports System.Data.Linq
Imports System.IO

Public Class FrmAcceuil
    Dim mmenu As New UcMenu
    Dim emp As New UCGestionEmployeV2
    Dim ben As New UcGestionBénéficiaireV2
    Dim opt As New UCParametres
    Dim horaire As New UcGrilleHoraire
    Dim ucaccompagnement As New UCGAccompagnement
    Dim ucRapport As New UCChoixRapport
    Dim liste As New ListViewEx
    Dim ModeEdition As Boolean = False
    Dim CurPage As Integer = 0
    Dim ValeurProg As Boolean = False
    Dim ListeEmploye As List(Of Employe)
    Private listeRecurrence As New List(Of Recurrence)
    Private trd As Thread

    Private Sub FrmAcceuil_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        FrmConnexion.Close()
    End Sub
    'Gestion du démarage de la page d'acceuil
    Private Sub FrmAcceuil_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'empConnecte.id = 1
        'empConnecte.gestionBeneficiaire = 2
        'empConnecte.gestionEmploye = 2
        'empConnecte.gestionHoraire = 1
        'empConnecte.nom = "chose binne"
        'Gestion des Contrôles utilisateurs sur leurs format
        mmenu.Dock = DockStyle.Fill

        emp.Dock = DockStyle.Fill

        ben.Dock = DockStyle.Fill
        opt.Dock = DockStyle.Fill
        horaire.Dock = DockStyle.Fill
        horaire.TypeRangees = UcGrilleHoraire.TypeDeTriEnum.Employes
        horaire.TypeColonnes = UcGrilleHoraire.TypeDeTriEnum.Jours
        horaire.TriEmployeParActivite = True
        SplitContainer1.Panel1.Controls.Clear()
        horaire.AllowDrop = True
        TogglePlageDetail(False)
        Using g As Graphics = horaire.CreateGraphics
            horaire.LargeurColonneMin = (g.MeasureString("99:99-99:99", New Font(horaire.Font, FontStyle.Bold)).Width + 40) * 1.33
        End Using

        horaire.init()

        Cal_Horaire.Value = Date.Today.AddDays(-Date.Today.DayOfWeek)
        Console.WriteLine(Cal_Horaire.Value.ToShortDateString)
        'Gestion du format de la liste de navigation des éléments
        liste.FullRowSelect = True
        liste.Dock = DockStyle.Fill
        liste.MultiSelect = False
        liste.HeaderStyle = ColumnHeaderStyle.Nonclickable
        Dim large As Integer = liste.Width / 2
        liste.Columns.Add("Nom", large)
        liste.Columns.Add("Prénom", large)
        'liste.Columns.Add("ID", 0)
        liste.View = View.Details
        liste.HeaderStyle = ColumnHeaderStyle.Nonclickable
        liste.HideSelection = False

        'Ajout des gestionnaires d'événements sur les différent boutons
        'TLPFond.Controls.Add(mmenu, 1, 1)
        SplitContainer1.Panel2.Controls.Add(mmenu)
        SplitContainer1.Panel1Collapsed = True
        AddHandler mmenu.BtnEmploye.Click, AddressOf Navigation
        AddHandler mmenu.BtnBeneficiaire.Click, AddressOf Navigation
        AddHandler mmenu.BtnParam.Click, AddressOf Navigation
        AddHandler mmenu.BtnHoraire.Click, AddressOf Navigation
        AddHandler mmenu.BtnAccompagnement.Click, AddressOf Navigation
        AddHandler mmenu.BtnRapports.Click, AddressOf Navigation
        AddHandler Cal_Horaire.Value_Changed, AddressOf ChangeDate
        'AddHandler emp.MouseEnter, AddressOf UserControl_MouseEnter
        AddHandler horaire.DragEnter, AddressOf Horaire_DragEnter
        AddHandler horaire.ColonneClickEvent, AddressOf SelectionJour
        AddHandler horaire.PlageSelected, AddressOf SelectionPlageHoraire
        AddHandler horaire.modification, AddressOf Modification
        AddHandler horaire.ViewDetail, AddressOf Button1_Click_1
        'AddHandler horaire.modification, AddressOf SelectionPlageHoraire
        'TEST
        AddHandler SplitContainer1.SplitterMoved, AddressOf FrmAcceuil_Resize
        AddHandler liste.ItemDeselecting, AddressOf liste_selection
        'empConnecte.id = 1
        'empConnecte.gestionBeneficiaire = 2
        'empConnecte.gestionEmploye = 2
        'empConnecte.gestionHoraire = 2
    End Sub
    Private Sub FrmAcceuil_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If liste.Visible = True Then
            Dim large As Integer = liste.Width / 2
            liste.Columns(0).Width = large - 3
            liste.Columns(1).Width = large - 2
        End If

    End Sub

    'Permet l'activation ou la désactivation des boutons de suppression, sauvegarde et annulation

    Private Sub Suppression(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Tsb_Del.Enabled = sender
    End Sub

    Private Sub Modification(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Tsb_Save.Enabled = sender
        Tsb_Revert.Enabled = sender
        ModeEdition = sender
    End Sub

    Private Sub annulation(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Tsb_Revert.Enabled = sender
    End Sub

    'Gestion de la partie employé.
#Region "Employe"

    'Gestion de la selection dans la liste de navigation.
    Private Sub ListeEmploye_selection(ByVal sender As System.Object, ByVal e As System.EventArgs)

        If Not liste.SelectedItems.Count = 0 And Not ModeEdition Then
            Tsb_Del.Enabled = True
            emp.chargerEmploye(liste.SelectedItems(0).SubItems(2).Text)
        End If
    End Sub
    Private Sub liste_selection(ByVal sender As Object, ByVal e As ItemChangingEventArgs)
        If Not liste.SelectedItems.Count = 0 And ModeEdition Then
            MessageBox.Show("Vous êtes présentement en édition. Veuillez sauvegarder vos modifications")
            e.Cancel = True
        End If
    End Sub
    'Gestion de la navigation dans la liste
    Private Sub ListeEmploye_Naviguer(ByVal sender As System.Object, ByVal e As System.EventArgs)
        emp.prog = True
        If IsNumeric(sender) Then
            For i = 0 To liste.Items.Count - 1
                If sender = liste.Items(i).SubItems(2).Text Then liste.Items(i).Selected = True
            Next
        Else
            'Navigation dans la liste
            Select Case sender
                Case "Aucun"
                    liste.SelectedItems.Clear()
                Case "Dernier"
                    liste.Items(liste.Items.Count - 1).Selected = True
                Case "Rafraichir"
                    liste.Items.Clear()
                    For Each i In bd.Employes
                        Dim list As New ListViewItem
                        If i.Supprime = True Then Continue For
                        list.Text = i.Nom
                        list.SubItems.AddRange({i.Prenom, i.ID})
                        liste.Items.Add(list)
                    Next
            End Select
        End If
        emp.prog = False
    End Sub

    Public ReadOnly Property getEmploye As UCGestionEmployeV2
        Get
            Return emp
        End Get
    End Property

#End Region

    'Gestion de la partie bénéficiaire
#Region "Beneficiaire"

    'Gestion de la navigation dans la liste
    Private Sub ListeBeneficiaire_Naviguer(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If IsNumeric(sender) Then
            For i = 0 To liste.Items.Count - 1
                If sender = liste.Items(i).SubItems(2).Text Then liste.Items(i).Selected = True
            Next
        Else
            Select Case sender
                Case "Aucun"
                    liste.SelectedItems.Clear()
                Case "Dernier"
                    liste.Items(liste.Items.Count - 1).Selected = True
                Case "Rafraichir"
                    liste.Items.Clear()
                    For Each i In bd.Beneficiaires
                        Dim list As New ListViewItem
                        If i.Supprime = True Then Continue For
                        list.Text = i.Nom
                        list.SubItems.AddRange({i.Prenom, i.ID})
                        liste.Items.Add(list)
                    Next
            End Select
        End If
        If liste.Items.Count = 0 Then
            ben.changerMode(Mode.ajout)
        End If
    End Sub

    'Gestion de la selection dans la liste de navigation.
    Private Sub ListeBeneficiaire_selection(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If Not liste.SelectedItems.Count = 0 Then
            Tsb_Del.Enabled = True
            ben.SelectionBeneficiaire((From x In bd.Beneficiaires Where x.ID = liste.SelectedItems(0).SubItems(2).Text Select x.ID).First)
        End If

    End Sub
#End Region

    'Gestion de la partie Options
#Region "Options"

    'Gestion des options
    Private Sub Options()
        'TLPFond.Controls.Remove(mmenu)
        'TLPFond.Controls.Add(opt, 1, 1)
        'BtnRetour.Visible = True

        'AddHandler BtnRetour.Click, AddressOf MenuOpt
    End Sub


    Private Sub MenuOpt(ByVal sender As System.Object, ByVal e As System.EventArgs)

        If (MsgBox("Voulez-vous retourner au menu.", 4, "CarpeDiem") = 6) Then
            'TLPFond.Controls.Remove(opt)
            'TLPFond.Controls.Add(mmenu)
            'RemoveHandler BtnRetour.Click, AddressOf MenuOpt
            'BtnRetour.Visible = False
        End If

    End Sub

#End Region

    'Vider les contrôles en cours
    Private Sub ClearControls()
        SplitContainer1.Panel1.Controls.Clear()
        SplitContainer1.Panel2.Controls.Clear()
        RemoveHandler liste.SelectedIndexChanged, AddressOf ListeEmploye_selection
        RemoveHandler liste.SelectedIndexChanged, AddressOf ListeBeneficiaire_selection
        TsbAccompagnement.Checked = False
        TsbEmploye.Checked = False
        TsbHome.Checked = False
        TsbBeneficiaire.Checked = False
        TsbHoraire.Checked = False
        TsbParam.Checked = False
        TsbRapports.Checked = False
        Tsb_Add.Visible = False
        Tsb_Del.Visible = False
        Tsb_Revert.Visible = False
        Tsb_Save.Visible = False
        Tsb_Autre.Visible = False
        ToolStripLabel1.Visible = False
        Tsb_Print.Visible = False
        liste.Items.Clear()
    End Sub

    'Gestion de la navigation du menu et de ses éléments
    Private Sub Navigation(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TsbHome.Click, TsbBeneficiaire.Click, TsbHoraire.Click, TsbEmploye.Click, TsbParam.Click, TsbAccompagnement.Click, TsbRapports.Click
        If CurPage > 0 AndAlso Not sender.checked Then
            If ModeEdition = True Then
                MessageBox.Show("Vous êtes présentement en édition. Veuillez sauvegarder vos modifications")
                Return
            End If
        End If

        If CurPage = 1 AndAlso Not sender.checked Then
            If Not horaire.Blocked Then
                MessageBox.Show("Veuillez bloquer l'horaire avant de quitter.", "Gestion CarpeDiem", MessageBoxButtons.OK, MessageBoxIcon.Information)

                Return
            End If
        End If
        Static aMode As String = "Home"

        'Suppression des gestionnaires d'événements en place
        Select Case aMode
            Case "Beneficiaire"
                RemoveHandler Tsb_Add.Click, AddressOf ben.Ajouter_Beneficiaire
                RemoveHandler Tsb_Del.Click, AddressOf ben.Enlever_Beneficiaire
                RemoveHandler Tsb_Revert.Click, AddressOf ben.Annuler_Beneficiaire
                RemoveHandler Tsb_Save.Click, AddressOf ben.InsererBeneficiaire
                RemoveHandler ben.suppression, AddressOf Suppression
                RemoveHandler ben.modification, AddressOf Modification
                RemoveHandler ben.annulation, AddressOf annulation
                RemoveHandler ben.listeBene, AddressOf ListeBeneficiaire_Naviguer
                RemoveHandler ben.UcGestionPersonneRessource1.ajout, AddressOf Modification
            Case "Horaire"

            Case "Employe"
                RemoveHandler Tsb_Add.Click, AddressOf emp.Ajouter_Employe
                RemoveHandler Tsb_Del.Click, AddressOf emp.Enlever_Employe
                RemoveHandler Tsb_Revert.Click, AddressOf emp.Annuler_Employe
                RemoveHandler Tsb_Save.Click, AddressOf emp.Sauver_Employe
                RemoveHandler emp.suppression, AddressOf Suppression
                RemoveHandler emp.modification, AddressOf Modification
                RemoveHandler emp.annulation, AddressOf annulation
                RemoveHandler emp.listeEmp, AddressOf ListeEmploye_Naviguer
            Case "Option"

            Case "Accompagnement"
                RemoveHandler Tsb_Add.Click, AddressOf ucaccompagnement.ViderChamp
                RemoveHandler Tsb_Del.Click, AddressOf ucaccompagnement.Supprimer
                RemoveHandler Tsb_Revert.Click, AddressOf ucaccompagnement.recharger
                RemoveHandler Tsb_Save.Click, AddressOf ucaccompagnement.Enregistrer
                RemoveHandler ucaccompagnement.suppression, AddressOf Suppression
                RemoveHandler ucaccompagnement.modification, AddressOf Modification
                RemoveHandler ucaccompagnement.annulation, AddressOf annulation
        End Select

        'Choix du menu
        Select Case sender.name.substring(3)
            'Retour au menu
            Case "Home"

                If Not TsbHome.Checked Then
                    CurPage = 0
                    ClearControls()
                    SplitContainer1.Panel2.Controls.Add(mmenu)
                    SplitContainer1.Panel1Collapsed = True
                    TsbHome.Checked = True
                End If

                'Ouverture de la page de gestion des bénéficiaires
            Case "Beneficiaire"
                If Not TsbBeneficiaire.Checked Then
                    'Vider les éléments en place et insertion des éléments de la page bénéficiaire
                    ben.ViderChamps()
                    ben.recharger()
                    ben.RechargerAffinite()
                    CurPage = 3
                    ClearControls()
                    SplitContainer1.Panel1.Controls.Add(liste)
                    SplitContainer1.Panel2.Controls.Add(ben)
                    SplitContainer1.Panel1Collapsed = False
                    Tsb_Del.Enabled = False
                    Tsb_Revert.Enabled = False
                    Tsb_Save.Enabled = False
                    Tsb_Add.Image = CarpeDiemHoraire.My.Resources.addBenIco
                    Tsb_Del.Image = CarpeDiemHoraire.My.Resources.delBenIco
                    Tsb_Add.ToolTipText = "Ajouter un Béneficiaire"
                    Tsb_Del.ToolTipText = "Supprimer un Béneficiaire"
                    Tsb_Revert.ToolTipText = "Annuler les modifications"
                    Tsb_Add.Visible = True
                    Tsb_Del.Visible = True
                    Tsb_Revert.Visible = True
                    Tsb_Save.Visible = True
                    TsbBeneficiaire.Checked = True
                    ben.Onglets(False)
                    'Mise à jour de la liste pour la gestion des bénéficiaires
                    AddHandler liste.SelectedIndexChanged, AddressOf ListeBeneficiaire_selection
                    liste.Items.Clear()
                    For Each i In bd.Beneficiaires
                        Dim list As New ListViewItem
                        If i.Supprime Then Continue For
                        list.Text = i.Nom
                        list.SubItems.AddRange({i.Prenom, i.ID})
                        liste.Items.Add(list)
                    Next
                    Dim large As Integer = liste.Width / 2
                    liste.Columns(0).Width = large - 3
                    liste.Columns(1).Width = large - 2
                    If liste.Items.Count > 0 Then
                        liste.Items(0).Selected = True
                    Else
                        ben.changerMode(Mode.ajout)
                    End If
                    'Ajout des gestionnaires d'événements
                    If empConnecte.gestionBeneficiaire = 2 Then
                        AddHandler Tsb_Add.Click, AddressOf ben.Ajouter_Beneficiaire
                        AddHandler Tsb_Del.Click, AddressOf ben.Enlever_Beneficiaire
                        AddHandler Tsb_Revert.Click, AddressOf ben.Annuler_Beneficiaire
                        AddHandler Tsb_Save.Click, AddressOf ben.InsererBeneficiaire
                        AddHandler ben.suppression, AddressOf Suppression
                        AddHandler ben.modification, AddressOf Modification
                        AddHandler ben.UcGestionPersonneRessource1.ajout, AddressOf Modification
                        AddHandler ben.annulation, AddressOf annulation
                        Tsb_Add.Visible = True
                        Tsb_Del.Visible = True
                        Tsb_Save.Visible = True
                        Tsb_Revert.Visible = True
                        ben.lectureSeule(False)
                    Else
                        Tsb_Add.Visible = False
                        Tsb_Del.Visible = False
                        Tsb_Save.Visible = False
                        Tsb_Revert.Visible = False
                        ben.lectureSeule(True)
                    End If
                    AddHandler ben.listeBene, AddressOf ListeBeneficiaire_Naviguer
                End If

                'Ouverture de la page de gestion des horaires
            Case "Horaire"
                If Not TsbHoraire.Checked Then
                    'Vider les éléments en place et insertion des éléments de la page horaire
                    CurPage = 1
                    ClearControls()
                    SplitContainer1.Panel1.Controls.Add(TC_Horaire)
                    horaire.Blocked = True
                    SplitContainer1.Panel2.Controls.Add(horaire)
                    SplitContainer1.Panel1Collapsed = False
                    TsbHoraire.Checked = True
                    If empConnecte.gestionHoraire = 1 Then
                        Tsb_Add.Image = CarpeDiemHoraire.My.Resources.lockedHor
                        Tsb_Add.ToolTipText = "Débloquer l'horaire"
                        Tsb_Add.Visible = True
                        Tsb_Save.Visible = True
                        Tsb_Save.Enabled = False
                        Tsb_Revert.Visible = True
                        Tsb_Revert.Enabled = False
                    Else

                    End If

                    Tsb_Autre.Visible = True
                    Tsb_Print.Visible = True


                    horaire.Semaine = Cal_Horaire.Value
                    ToolStripLabel1.Text = "Semaine du " + Cal_Horaire.Value.Day.ToString() + " " + Cal_Horaire.Value.ToString("MMMM", CultureInfo.GetCultureInfo("fr-CA"))
                    ToolStripLabel1.Visible = True

                    horaire.init()

                    'Liste des plages
                    RemplireListePlage()
                    RemplireListeRecurrence()
                    'Load les employés dans un autre thread pour pas geler l'interface
                    trd = New Thread(AddressOf LoadDataAsync)
                    trd.Start()
                End If

                'Ouverture de la page de gestion des employés
            Case "Employe"
                If Not TsbEmploye.Checked Then
                    'Vider les éléments en place et insertion des éléments de la page Employé
                    emp.RechargerVilles()
                    emp.RechargerAffinite()
                    emp.RechargerFormation()
                    CurPage = 2
                    ClearControls()
                    SplitContainer1.Panel1.Controls.Add(liste)
                    SplitContainer1.Panel2.Controls.Add(emp)

                    SplitContainer1.Panel1Collapsed = False

                    Tsb_Del.Enabled = False
                    Tsb_Revert.Enabled = False
                    Tsb_Save.Enabled = False
                    Tsb_Add.Image = CarpeDiemHoraire.My.Resources.addEmpIco
                    Tsb_Del.Image = CarpeDiemHoraire.My.Resources.delEmpIco
                    Tsb_Add.ToolTipText = "Ajouter un employé"
                    Tsb_Del.ToolTipText = "Supprimer un employé"

                    Tsb_Revert.ToolTipText = "Annuler les modifications"

                    Tsb_Add.Visible = True
                    Tsb_Del.Visible = True
                    Tsb_Revert.Visible = True
                    Tsb_Save.Visible = True
                    TsbEmploye.Checked = True

                    'Mise à jour de la liste pour la gestion des employés
                    emp.onglets(False)
                    liste.Items.Clear()
                    Dim empl As List(Of DAL.Employe)
                    If empConnecte.gestionEmploye = 0 Then
                        empl = (From x In bd.Employes Where x.ID = empConnecte.id Select x).ToList
                    Else
                        empl = (From x In bd.Employes Where x.ID And x.Supprime = False Select x).ToList
                    End If
                    For Each i In empl
                        Dim list As New ListViewItem
                        If i.Supprime Then Continue For
                        list.Text = i.Nom
                        list.SubItems.AddRange({i.Prenom, i.ID})
                        liste.Items.Add(list)
                    Next
                    Dim large As Integer = liste.Width / 2
                    liste.Columns(0).Width = large - 3
                    liste.Columns(1).Width = large - 2
                    AddHandler liste.SelectedIndexChanged, AddressOf ListeEmploye_selection
                    'Ajout des gestionnaires d'événements
                    'CHECK : j'ai enlever des handler parce qu'ils s'ajoutaient 2 fois (a cause du droit de gestion plus bas)
                    AddHandler emp.listeEmp, AddressOf ListeEmploye_Naviguer

                    If Not empConnecte.gestionEmploye = 2 Then
                        liste.Items(0).Selected = True
                        Tsb_Add.Visible = False
                        Tsb_Del.Visible = False
                    Else
                        liste.Items(0).Selected = True
                        Tsb_Add.Visible = True
                        Tsb_Del.Visible = True
                        AddHandler Tsb_Add.Click, AddressOf emp.Ajouter_Employe
                        AddHandler Tsb_Del.Click, AddressOf emp.Enlever_Employe
                        AddHandler Tsb_Revert.Click, AddressOf emp.Annuler_Employe
                        AddHandler Tsb_Save.Click, AddressOf emp.Sauver_Employe
                        AddHandler emp.modification, AddressOf Modification
                        AddHandler emp.suppression, AddressOf Suppression
                        AddHandler emp.listeEmp, AddressOf ListeEmploye_Naviguer
                    End If
                End If
            Case "Param"
                If Not TsbParam.Checked Then
                    'Vider les éléments en place et insertion des éléments de la page Option
                    CurPage = 4
                    ClearControls()
                    opt = New UCParametres
                    opt.Dock = DockStyle.Fill
                    SplitContainer1.Panel2.Controls.Add(opt)
                    SplitContainer1.Panel1Collapsed = True
                    TsbParam.Checked = True
                End If
            Case "Accompagnement"
                If Not TsbAccompagnement.Checked Then
                    CurPage = 5
                    ClearControls()
                    ucaccompagnement = New UCGAccompagnement
                    ucaccompagnement.Dock = DockStyle.Fill
                    Tsb_Del.Enabled = False
                    Tsb_Revert.Enabled = False
                    Tsb_Save.Enabled = False
                    Tsb_Add.Image = CarpeDiemHoraire.My.Resources.addAccIco
                    Tsb_Del.Image = CarpeDiemHoraire.My.Resources.delAccIco
                    Tsb_Add.ToolTipText = "Ajouter un Accompagnement"
                    Tsb_Del.ToolTipText = "Supprimer un Accompagnement"

                    Tsb_Revert.ToolTipText = "Annuler les modifications"

                    Tsb_Add.Visible = True
                    Tsb_Del.Visible = True
                    Tsb_Revert.Visible = True
                    Tsb_Save.Visible = True
                    TsbAccompagnement.Checked = True
                    AddHandler Tsb_Add.Click, AddressOf ucaccompagnement.ViderChamp
                    AddHandler Tsb_Del.Click, AddressOf ucaccompagnement.Supprimer
                    AddHandler Tsb_Revert.Click, AddressOf ucaccompagnement.recharger
                    AddHandler Tsb_Save.Click, AddressOf ucaccompagnement.Enregistrer
                    AddHandler ucaccompagnement.suppression, AddressOf Suppression
                    AddHandler ucaccompagnement.modification, AddressOf Modification
                    AddHandler ucaccompagnement.annulation, AddressOf annulation
                    SplitContainer1.Panel2.Controls.Add(ucaccompagnement)
                    SplitContainer1.Panel1Collapsed = True
                End If
            Case "Rapports"
                If Not TsbRapports.Checked Then
                    'Affichage de la page de rapports
                    CurPage = 6
                    ClearControls()
                    ucRapport = New UCChoixRapport
                    ucRapport.Dock = DockStyle.Fill
                    SplitContainer1.Panel2.Controls.Add(ucRapport)
                    SplitContainer1.Panel1Collapsed = True
                    TsbRapports.Checked = True
                End If
        End Select
        aMode = sender.name.substring(3)
    End Sub

    Private DateChangeProg As Boolean = False

    'Gestion des intervales de date de l'horaire
    Private Sub ChangeDate(ByVal sender As System.Object, ByVal e As System.EventArgs)
        horaire.Semaine = Cal_Horaire.Value

        If Cal_Horaire.ModeSelection = UcCalendrier.ModeSelectionEnum.Semaine And horaire.Blocked Then
            LoadPlageFromDate()
        ElseIf Cal_Horaire.ModeSelection = UcCalendrier.ModeSelectionEnum.JourDansSemaine And Not DateChangeProg Then
            horaire.PlacerPlages()
            horaire.AjusterPlages()
            horaire.init()
        End If

        Dim weektext As String = String.Empty
        If Cal_Horaire.ModeSelection = UcCalendrier.ModeSelectionEnum.Semaine Then

            weektext = "Semaine du " + Cal_Horaire.Value.Day.ToString() + " " + Cal_Horaire.Value.ToString("MMMM", CultureInfo.GetCultureInfo("fr-CA"))
        ElseIf Cal_Horaire.ModeSelection = UcCalendrier.ModeSelectionEnum.JourDansSemaine Then
            weektext = StrConv(Cal_Horaire.Value.ToString("dddd", CultureInfo.GetCultureInfo("fr-CA")), VbStrConv.ProperCase) _
                + " le " + Cal_Horaire.Value.Day.ToString() + " " + Cal_Horaire.Value.ToString("MMMM", CultureInfo.GetCultureInfo("fr-CA"))
        End If
        ToolStripLabel1.Text = weektext

    End Sub

    Private Sub LoadPlageFromDate()
        horaire.Reset()
        Dim dimanche As Date = Cal_Horaire.Value.AddDays(-Cal_Horaire.Value.DayOfWeek)
        horaire.SetPlageList((From x In bd.PlageHoraires _
                          Where x.Date.DayOfYear >= dimanche.DayOfYear AndAlso x.Date.DayOfYear < dimanche.DayOfYear + 7 _
                          And (x.Employe1.Supprime = False) Select x).ToList())
        Console.WriteLine("plage count = " + horaire.GetPlages().Count.ToString)
        If Not DateChangeProg Then
            horaire.PlacerPlages()
            horaire.AjusterPlages()
            horaire.init()
        End If

    End Sub

    'Gestion de la selection des jours dans l'horaire
    Private Sub SelectionJour(ByVal sender As System.Object, ByVal e As System.EventArgs)
        DateChangeProg = True
        Cal_Horaire.ModeSelection = UcCalendrier.ModeSelectionEnum.JourDansSemaine
        Cal_Horaire.Value = Cal_Horaire.Value.AddDays(-Cal_Horaire.Value.DayOfWeek + Convert.ToInt32(sender))
        Cal_Horaire.ChangerMois(New Date(Cal_Horaire.Value.Year, Cal_Horaire.Value.Month, 1))
        Cal_Horaire.GoToValue()
        Cal_Horaire.MonthLock = True

        DateChangeProg = False
        Tsb_Autre.Enabled = True
    End Sub

    Private Sub Tsb_Add_MouseEnter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Tsb_Add.MouseEnter
        If SplitContainer1.Panel2.Controls.Contains(horaire) Then
            If horaire.Blocked Then
                Tsb_Add.Image = CarpeDiemHoraire.My.Resources.unlockedHor
            Else
                Tsb_Add.Image = CarpeDiemHoraire.My.Resources.lockedHor
            End If
        End If
    End Sub

    Private Sub Tsb_Add_MouseLeave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Tsb_Add.MouseLeave
        If SplitContainer1.Panel2.Controls.Contains(horaire) Then
            If Not horaire.Blocked Then
                Tsb_Add.Image = CarpeDiemHoraire.My.Resources.unlockedHor
            Else
                Tsb_Add.Image = CarpeDiemHoraire.My.Resources.lockedHor
            End If
        End If
    End Sub

    Private Sub Tsb_Add_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Tsb_Add.Click
        If CurPage = 1 Then
            If Not horaire.Blocked AndAlso ModeEdition Then 'is unlocked and editing not saved
                Dim result As DialogResult = MessageBox.Show("Voulez-vous enregistrer les modifications avant de bloquer l'horaire?", "Confirmation", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button3)
                If result = Windows.Forms.DialogResult.Yes Then
                    Tsb_Save_Click(horaire, Nothing)
                ElseIf result = Windows.Forms.DialogResult.No Then
                    Modification(False, Nothing)
                    bd.Refresh(Data.Linq.RefreshMode.OverwriteCurrentValues, bd.PlageHoraires)
                    bd.Refresh(Data.Linq.RefreshMode.OverwriteCurrentValues, bd.Taches)

                    LoadPlageFromDate()
                    SelectionPlageHoraire(horaire, Nothing)
                ElseIf result = Windows.Forms.DialogResult.Cancel Then
                    Return
                End If
            Else
                If Cal_Horaire.Value.AddDays(-Cal_Horaire.Value.DayOfWeek) < Date.Today.AddDays(-Date.Today.DayOfWeek) And horaire.Blocked Then
                    If MessageBox.Show("Cette semaine est passée, voulez-vous vraiment modifier l'horaire?", "Confirmation", _
                                    MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Cancel Then
                        Return
                    End If

                End If
            End If
            horaire.Blocked = Not horaire.Blocked
            BtnPlacerRec.Enabled = Not horaire.Blocked
            BtnPlacerSelRec.Enabled = Not horaire.Blocked
            If Not Cal_Horaire.ModeSelection = UcCalendrier.ModeSelectionEnum.JourDansSemaine Then
                Cal_Horaire.MonthLock = Not horaire.Blocked
            End If

            Cal_Horaire.SelectionLock = Not horaire.Blocked
            If Not horaire.Blocked Then
                Tsb_Add.Image = CarpeDiemHoraire.My.Resources.unlockedHor
                Tsb_Add.ToolTipText = "Bloquer l'horaire"

            Else
                Tsb_Add.Image = CarpeDiemHoraire.My.Resources.lockedHor
                Tsb_Add.ToolTipText = "Débloquer l'horaire"
            End If
            If Not horaire.SelectedPlage Is Nothing Then
                TogglePlageDetail(Not horaire.Blocked)
            End If
        End If
    End Sub

    Private Sub TogglePlageDetail(ByVal state As Boolean)
        For Each ctrl As Control In Tlp_PlageDetail.Controls
            If TypeOf ctrl Is TextBox Or TypeOf ctrl Is DateTimePicker Or TypeOf ctrl Is NumericUpDown Or TypeOf ctrl Is Button Then
                ctrl.Enabled = state
            End If
        Next
        If Not horaire.SelectedPlage Is Nothing Then
            Button1.Enabled = True
        End If
    End Sub

    Private Sub Tsb_Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Tsb_Save.Click
        If CurPage = 1 Then
            Tsb_Save.Enabled = False
            Tsb_Add.Enabled = True
            Dim hor As Horaire
            Dim dimanche As Date = Cal_Horaire.Value.AddDays(-Cal_Horaire.Value.DayOfWeek)
            Console.WriteLine(Cal_Horaire.Value.ToString())

            If (From x In bd.Horaires Where x.DateDimanche = dimanche Select x).Count() = 0 Then
                hor = New Horaire
                hor.DateDimanche = dimanche
                bd.Horaires.InsertOnSubmit(hor)
            Else
                hor = (From x In bd.Horaires Where x.DateDimanche = dimanche Select x).First
            End If

            For Each plage As PlageHoraire In horaire.GetPlages()
                plage.Horaire1 = hor
            Next

            For Each plage As PlageHoraire In horaire.GetPlages().Where(Function(c) c.ID = 0)
                bd.PlageHoraires.InsertOnSubmit(plage)
            Next
            bd.SubmitChanges()
            Modification(False, Nothing)
        End If

    End Sub

#Region "DragDropOverGrid"

    'Gestion des déplacements d'éléments sur l'horaire
    Private Sub Lv_Plages_ItemDrag(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ItemDragEventArgs) Handles Lv_Plages.ItemDrag
        If Not horaire.Blocked Then
            DoDragDrop(Lv_Plages.SelectedItems(0).Tag.ToString, DragDropEffects.Move)

        End If

    End Sub

    Private Sub Horaire_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs)

        Console.WriteLine("enter drag")
        If (e.Data.GetDataPresent(DataFormats.Text)) Then

            'e.Effect = DragDropEffects.All
            horaire.AddPlageStocke((From x In bd.PlageHoraireStockes Where x.ID = Convert.ToInt32(e.Data.GetData(DataFormats.Text)) Select x).First)
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub

#End Region

    Private Sub Tsb_Autre_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Tsb_Autre.Click
        If CurPage = 1 Then
            Cal_Horaire.ModeSelection = UcCalendrier.ModeSelectionEnum.Semaine
            If horaire.Blocked Then
                Cal_Horaire.MonthLock = False
            End If
            Tsb_Autre.Enabled = False
            DateChangeProg = True
            Cal_Horaire.Value = Cal_Horaire.Value.AddDays(-Cal_Horaire.Value.DayOfWeek)
            DateChangeProg = False
            horaire.SwitchView(UcGrilleHoraire.TypeDeTriEnum.Jours)

        End If
    End Sub

    Private Sub Tsb_Revert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Tsb_Revert.Click
        If CurPage = 1 Then
            If (MessageBox.Show("Êtes-vous sûr de vouloir annuler les modofications apportées depuis la derniere sauvegarde?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes) Then
                Modification(False, Nothing)

                DiscardInsertsAndDeletes(bd)

                bd.Refresh(Data.Linq.RefreshMode.OverwriteCurrentValues, bd.PlageHoraires)
                bd.Refresh(Data.Linq.RefreshMode.OverwriteCurrentValues, bd.Taches)

                LoadPlageFromDate()
                SelectionPlageHoraire(horaire, Nothing)
            End If
        End If

    End Sub

    Public Sub DiscardInsertsAndDeletes(ByVal data As DataContext)
        ' Get the changes
        Dim changes = data.GetChangeSet()
        ' Delete the insertions
        For Each insertion In changes.Inserts
            data.GetTable(insertion.GetType).DeleteOnSubmit(insertion)
        Next
        ' Insert the deletions
        For Each deletion In changes.Deletes
            data.GetTable(deletion.GetType).InsertOnSubmit(deletion)
        Next
    End Sub

#Region "DetailPlage"

    Private Sub SelectionPlageHoraire(ByVal sender As System.Object, ByVal e As System.EventArgs)

        If Not horaire.SelectedPlage Is Nothing Then
            If TC_Horaire.SelectedIndex = 0 Then
                TC_Horaire.SelectedIndex = 1
            End If
            TogglePlageDetail(Not horaire.Blocked)
            ValeurProg = True
            UpdatePlageDetail()
            ValeurProg = False
        Else
            ValeurProg = True
            Tb_NomPlage.Text = String.Empty
            Pb_CouleurPlage.BackColor = SystemColors.Control

            ValeurProg = False
            TogglePlageDetail(False)
        End If

    End Sub

    Private Sub UpdatePlageDetail()
        Tb_NomPlage.Text = horaire.SelectedPlage.plage.Nom
        Pb_CouleurPlage.BackColor = ColorTranslator.FromHtml(horaire.SelectedPlage.plage.Couleur)
        ValeurProg = True

        TbHeureDeb.Text = horaire.SelectedPlage.plage.Date.ToString("H'h'mm")
        TbHeureFin.Text = horaire.SelectedPlage.plage.Date.AddMinutes(horaire.SelectedPlage.plage.Duree).ToString("H'h'mm")
        TbDuree.Text = Date.Today.AddMinutes(horaire.SelectedPlage.plage.Duree).ToString("H'h'mm")
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_ColorPicker.Click
        If Not horaire.SelectedPlage Is Nothing Then
            Dim diag As New FrmColorPicker()
            diag.Value = horaire.SelectedPlage.Couleur
            If diag.ShowDialog = DialogResult.OK Then
                horaire.SelectedPlage.plage.Couleur = ColorTranslator.ToHtml(diag.Value)
                Pb_CouleurPlage.BackColor = diag.Value
                horaire.PlacerPlages()
                horaire.init()

            End If
        End If
    End Sub

#End Region

    Private Sub SetHoraireEmploye()
        If horaire.InvokeRequired Then
            Invoke(New MethodInvoker(AddressOf SetHoraireEmploye))
        Else
            horaire.SetEmployeList(ListeEmploye)
            horaire.init()
            If horaire.TypeRangees = UcGrilleHoraire.TypeDeTriEnum.Employes Then
                Dim maxName As String = (From x In ListeEmploye Order By (x.Nom + x.Prenom).Length Descending Select (x.Nom + ", " + x.Prenom)).First
                Using g As Graphics = horaire.CreateGraphics
                    horaire.VSplitterDistance = g.MeasureString(maxName, horaire.Font).Width + horaire.HauteurRangeeMin + 25
                End Using
            End If
            Cal_Horaire.Value = Cal_Horaire.Value
        End If
    End Sub

    Private Sub LoadDataAsync()
        'bd.Connection.Open()
        ListeEmploye = (From x In bd.Employes Where x.Supprime = False Select x).ToList()
        SetHoraireEmploye()
    End Sub

    Private Sub Btn_AddPlageStock_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_AddPlageStock.Click

        Using frm As New FrmEditionPlage()
            frm.ModeEdition = FrmEditionPlage.TypeEdition.AjoutPlageStock
            If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then
                Using nbd As New BDCarpeDiemDataContext
                    Dim nPlageStock As New PlageHoraireStocke()
                    nPlageStock.Nom = frm.Titre
                    nPlageStock.Description = frm.Description
                    nPlageStock.HeureDebut = frm.DateDebut
                    nPlageStock.Duree = frm.Duree.TotalMinutes
                    nPlageStock.Couleur = ColorTranslator.ToHtml(frm.Couleur)
                    nbd.PlageHoraireStockes.InsertOnSubmit(nPlageStock)
                    nbd.SubmitChanges()
                End Using

                RemplireListePlage()
            End If
        End Using
    End Sub

    Private Sub RemplireListePlage()
        Lv_Plages.Items.Clear()
        Dim imglist As New ImageList
        imglist.ImageSize = New Size(20, 20)
        Dim ctr As Integer = 0
        Using bdc As New BDCarpeDiemDataContext
            For Each plage As PlageHoraireStocke In From x In bdc.PlageHoraireStockes Select x

                Dim itm As New ListViewItem
                itm.Text = plage.Nom
                itm.ImageIndex = ctr
                itm.Tag = plage.ID
                ctr += 1
                Lv_Plages.Items.Add(itm)
                Dim img As New Bitmap(20, 20)
                Using g As Graphics = Graphics.FromImage(img)
                    g.Clear(System.Drawing.ColorTranslator.FromHtml(plage.Couleur))
                End Using
                imglist.Images.Add(img)

            Next
        End Using

        Lv_Plages.SmallImageList = imglist
    End Sub

    Private Sub RemplireListeRecurrence()
        LvRecurrence.Items.Clear()
        listeRecurrence.Clear()
        Dim imgListCouleurRecurrence As New ImageList
        imgListCouleurRecurrence.ImageSize = New Size(20, 20)
        Dim ctr As Integer = 0
        Using bdc As New BDCarpeDiemDataContext
            For Each recur In (From x In bdc.Recurrences Select x).ToList
                listeRecurrence.Add(recur)
                Dim itm As New ListViewItem
                itm.Text = recur.Nom
                itm.ImageIndex = ctr
                itm.Tag = recur.ID
                Dim txtJour As String = String.Empty
                Dim nomEmp As String = recur.Employe1.Prenom + " " + recur.Employe1.Nom
                Dim heureDebut As TimeSpan = recur.Heure.Value
                Dim heureFin As TimeSpan = recur.Heure.Value.Add(TimeSpan.FromMinutes(recur.Durée.Value))
                accDate = heureDebut.Hours.ToString + "h" + heureDebut.ToString("mm") + "-" + heureFin.Hours.ToString + "h" + heureFin.ToString("mm")
                Select Case recur.Jour
                    Case 0
                        txtJour = "Dimanche"
                    Case 1
                        txtJour = "Lundi"
                    Case 2
                        txtJour = "Mardi"
                    Case 3
                        txtJour = "Mercredi"
                    Case 4
                        txtJour = "Jeudi"
                    Case 5
                        txtJour = "Vendredi"
                    Case 6
                        txtJour = "Samedi"
                    Case 7
                        txtJour = "Tous les jours"
                    Case Else
                        txtJour = "Jamais"
                End Select
                If recur.Accompagnement.HasValue AndAlso recur.Accompagnement Then
                    Dim nomBen As String
                    nomBen = recur.Beneficiaire1.Prenom + " " + recur.Beneficiaire1.Nom
                    itm.ToolTipText = nomBen + " acc. par " + nomEmp + Environment.NewLine + txtJour + " à " + accDate
                Else
                    itm.ToolTipText = "Par " + nomEmp + Environment.NewLine + txtJour + " à " + accDate
                End If

                ctr += 1
                LvRecurrence.Items.Add(itm)
                Dim img As New Bitmap(20, 20)
                Using g As Graphics = Graphics.FromImage(img)
                    g.Clear(System.Drawing.ColorTranslator.FromHtml(recur.Couleur))
                End Using
                imgListCouleurRecurrence.Images.Add(img)

            Next
        End Using

        LvRecurrence.SmallImageList = imgListCouleurRecurrence
    End Sub

    Private Sub Lv_Plages_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Lv_Plages.MouseDoubleClick
        If Lv_Plages.SelectedItems.Count = 1 Then
            Using frm As New FrmEditionPlage()
                frm.ModeEdition = FrmEditionPlage.TypeEdition.AjoutPlageStock
                Using nbd As New BDCarpeDiemDataContext
                    Dim plageStock As PlageHoraireStocke = (From x As PlageHoraireStocke In nbd.PlageHoraireStockes Where x.ID = CType(Lv_Plages.SelectedItems(0).Tag, Integer) Select x).First
                    frm.Titre = plageStock.Nom
                    frm.Description = plageStock.Description
                    frm.Couleur = ColorTranslator.FromHtml(plageStock.Couleur)
                    frm.Duree = TimeSpan.FromMinutes(plageStock.Duree)
                    If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then

                        plageStock.Nom = frm.Titre
                        plageStock.Description = frm.Description
                        plageStock.Duree = frm.Duree.TotalMinutes
                        plageStock.HeureDebut = frm.DateDebut
                        plageStock.Couleur = ColorTranslator.ToHtml(frm.Couleur)
                        nbd.SubmitChanges()
                        RemplireListePlage()
                    End If
                End Using
            End Using
        End If
    End Sub

    Private Sub Lv_Plages_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Lv_Plages.SelectedIndexChanged
        Btn_ModifierPlageStock.Enabled = (Lv_Plages.SelectedItems.Count = 1)
    End Sub

    Private Sub Btn_ModifierPlageStock_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_ModifierPlageStock.Click
        If Lv_Plages.SelectedItems.Count = 1 Then
            Using frm As New FrmEditionPlage()
                frm.ModeEdition = FrmEditionPlage.TypeEdition.AjoutPlageStock
                Using nbd As New BDCarpeDiemDataContext
                    Dim plageStock As PlageHoraireStocke = (From x As PlageHoraireStocke In nbd.PlageHoraireStockes Where x.ID = CType(Lv_Plages.SelectedItems(0).Tag, Integer) Select x).First
                    frm.Titre = plageStock.Nom
                    frm.Description = plageStock.Description
                    frm.Couleur = ColorTranslator.FromHtml(plageStock.Couleur)
                    frm.Duree = TimeSpan.FromMinutes(plageStock.Duree)
                    frm.DateDebut = plageStock.HeureDebut
                    If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then

                        plageStock.Nom = frm.Titre
                        plageStock.Description = frm.Description
                        plageStock.Duree = frm.Duree.TotalMinutes
                        plageStock.HeureDebut = frm.DateDebut
                        plageStock.Couleur = ColorTranslator.ToHtml(frm.Couleur)

                        nbd.SubmitChanges()
                        RemplireListePlage()
                    End If
                End Using
            End Using
        End If
    End Sub

    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Using frm As New FrmEditionPlage()
            If horaire.Blocked Then
                frm.ModeEdition = FrmEditionPlage.TypeEdition.LecturePlage
            Else
                frm.ModeEdition = FrmEditionPlage.TypeEdition.ModificationPlage
            End If

            frm.Titre = horaire.SelectedPlage.plage.Nom
            frm.Description = horaire.SelectedPlage.plage.Note
            If horaire.SelectedPlage.plage.Accompagnement Then
                frm.Accompagnement = True
                Dim benPlage As Beneficiaire = (From x In bd.Beneficiaires Where x.ID = horaire.SelectedPlage.plage.Beneficiaire Select x).First
                frm.Beneficiaire = benPlage.Nom + ", " + benPlage.Prenom
            End If
            frm.QuartArriere = IIf(Not horaire.SelectedPlage.plage.QuartArriere Is Nothing, horaire.SelectedPlage.plage.QuartArriere, False)
            frm.Couleur = ColorTranslator.FromHtml(horaire.SelectedPlage.plage.Couleur)
            frm.DateDebut = New TimeSpan(horaire.SelectedPlage.plage.Date.TimeOfDay.Ticks)
            frm.Duree = TimeSpan.FromMinutes(horaire.SelectedPlage.plage.Duree)
            frm.ListeTache = horaire.SelectedPlage.plage.Taches.ToList()

            If Not horaire.SelectedPlage.plage.QuartArriere Is Nothing Then
                frm.QuartArriere = horaire.SelectedPlage.plage.QuartArriere
            Else
                frm.QuartArriere = False
            End If

            If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then
                Console.WriteLine(frm.ValueModified)
                If frm.ValueModified Then
                    Modification(True, Nothing)
                End If
                horaire.SelectedPlage.plage.Nom = frm.Titre
                horaire.SelectedPlage.plage.Note = frm.Description
                Dim oldDate As Date = horaire.SelectedPlage.plage.Date
                horaire.SelectedPlage.plage.Date = New Date(oldDate.Year, oldDate.Month, oldDate.Day, 0, 0, 0).AddTicks(frm.DateDebut.Ticks)
                horaire.SelectedPlage.plage.Duree = frm.Duree.TotalMinutes
                horaire.SelectedPlage.plage.QuartArriere = frm.QuartArriere
                horaire.SelectedPlage.plage.Couleur = ColorTranslator.ToHtml(frm.Couleur)
                Dim listeTache As New System.Data.Linq.EntitySet(Of Tache)
                listeTache.AddRange(frm.ListeTache)
                horaire.SelectedPlage.plage.Taches = listeTache
                UpdatePlageDetail()
                horaire.PlacerPlages()
                horaire.init()
            End If
        End Using
    End Sub

    Private Sub Tsb_Print_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Tsb_Print.Click
        If CurPage = 1 And horaire.Blocked Then

            Using diag As New FrmImprimeHoraire
                diag.DateHoraire = Cal_Horaire.Value
                diag.ShowDialog()
            End Using

        Else
            MessageBox.Show("Veuillez bloquer l'horaire avant d'imprimmer.", "Gestion CarpeDiem", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

    Private Sub UserControl_MouseEnter(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim usrCtr As Control = sender
        usrCtr.Select()
        Console.WriteLine("select")
    End Sub

    Private Sub DéconnexionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DéconnexionToolStripMenuItem.Click
        If ModeEdition Or (CurPage = 1 AndAlso Not horaire.Blocked) Then
            If (CurPage = 1 AndAlso Not horaire.Blocked) Then
                MessageBox.Show("Veuillez bloquer l'horaire avant de quitter.", "Gestion CarpeDiem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Else
                MessageBox.Show("Veuillez sauvegarder avant de quitter.", "Gestion CarpeDiem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End If
            Return
        End If
        If MsgBox("Êtes-vous sur de vouloir vous déconnecter?", MsgBoxStyle.YesNo) = 6 Then
            Me.Hide()
            FrmConnexion.tbPassword.Text = String.Empty
            FrmConnexion.Show()
            TsbHome.PerformClick()
        End If
    End Sub

    Private Sub QuitterToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles QuitterToolStripMenuItem.Click
        If ModeEdition Or (CurPage = 1 AndAlso Not horaire.Blocked) Then
            If (CurPage = 1 AndAlso Not horaire.Blocked) Then
                MessageBox.Show("Veuillez bloquer l'horaire avant de quitter.", "Gestion CarpeDiem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Else
                MessageBox.Show("Veuillez sauvegarder avant de quitter.", "Gestion CarpeDiem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End If

            Return
        End If
        If MsgBox("Êtes-vous sur de vouloir quitter?", MsgBoxStyle.YesNo) = 6 Then End
    End Sub

    Public Sub Frm_Acceuil_Show(ByVal sender As Object, ByVal e As EventArgs) Handles Me.VisibleChanged
        If Visible = True Then
            If empConnecte.gestionBeneficiaire = 0 Then
                TsbBeneficiaire.Visible = False
                mmenu.BtnBeneficiaire.Enabled = False
                mmenu.BtnBeneficiaire.BackColor = Color.FromArgb(240, 240, 240)
                
            Else
                TsbBeneficiaire.Visible = True
                mmenu.BtnBeneficiaire.Enabled = True
                mmenu.BtnBeneficiaire.BackColor = Color.White
                
            End If

            If empConnecte.gestionHoraire = 0 Then
                TsbAccompagnement.Visible = False
                Tsb_Save.Visible = False
                Tsb_Add.Visible = False
                mmenu.BtnAccompagnement.Enabled = False
                mmenu.BtnAccompagnement.BackColor = Color.FromArgb(240, 240, 240)
                TsbParam.Visible = False
                mmenu.BtnParam.Enabled = False
                mmenu.BtnParam.BackColor = Color.FromArgb(240, 240, 240)
                TsbRapports.Visible = False
                mmenu.BtnRapports.Enabled = False
                mmenu.BtnRapports.BackColor = Color.FromArgb(240, 240, 240)
                TC_Horaire.TabPages.Remove(TabPage3)
                GbPlageStock.Visible = False
            Else
                TsbAccompagnement.Visible = True
                mmenu.BtnAccompagnement.Enabled = True
                mmenu.BtnAccompagnement.BackColor = Color.White
                TsbParam.Visible = True
                mmenu.BtnParam.Enabled = True
                mmenu.BtnParam.BackColor = Color.White
                TsbRapports.Visible = True
                mmenu.BtnRapports.Enabled = True
                mmenu.BtnRapports.BackColor = Color.White
                GbPlageStock.Visible = True
                If Not TC_Horaire.TabPages.Contains(TabPage3) Then
                    TC_Horaire.TabPages.Add(TabPage3)
                End If
            End If
        End If
    End Sub

    Private Sub BtnAddRec_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnAddRec.Click
        Using diag As New FrmRecurrence()
            diag.ModeEdition = FrmRecurrence.TypeEdition.AjoutRecurrence
            If diag.ShowDialog() = Windows.Forms.DialogResult.OK Then
                Using nbd As New BDCarpeDiemDataContext
                    Dim nRec As New Recurrence()
                    nRec.Nom = diag.Titre
                    nRec.Note = diag.Description
                    nRec.Heure = diag.DateDebut
                    nRec.Durée = diag.Duree.TotalMinutes
                    nRec.Employe = diag.EmployeRecurrence.ID
                    nRec.Jour = diag.Jour
                    nRec.Couleur = ColorTranslator.ToHtml(diag.Couleur)
                    nbd.Recurrences.InsertOnSubmit(nRec)
                    nbd.SubmitChanges()
                End Using
                RemplireListeRecurrence()
            End If

        End Using
    End Sub

    Private Sub BtnEditRec_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnEditRec.Click
        If LvRecurrence.SelectedItems.Count <> 1 Then
            BtnEditRec.Enabled = False
            Return
        End If
        Using diag As New FrmRecurrence()
            Using nbd As New BDCarpeDiemDataContext
                diag.ModeEdition = FrmRecurrence.TypeEdition.ModificationRecurrence
                Dim recur As Recurrence = (From x In nbd.Recurrences Where x.ID = CType(LvRecurrence.SelectedItems(0).Tag, Integer) Select x).First
                diag.EmployeRecurrence = recur.Employe1
                diag.DateDebut = recur.Heure
                diag.Duree = TimeSpan.FromMinutes(recur.Durée)
                diag.Titre = recur.Nom
                diag.Description = recur.Note
                diag.Couleur = ColorTranslator.FromHtml(recur.Couleur)
                diag.Jour = recur.Jour
                If diag.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    recur.Employe1 = (From x In nbd.Employes Where x.ID = diag.EmployeRecurrence.ID Select x).First
                    recur.Durée = diag.Duree.TotalMinutes
                    recur.Heure = diag.DateDebut
                    recur.Nom = diag.Titre
                    recur.Note = diag.Description
                    recur.Couleur = ColorTranslator.ToHtml(diag.Couleur)
                    recur.Jour = diag.Jour
                    nbd.SubmitChanges()

                    RemplireListeRecurrence()
                End If
            End Using
        End Using
    End Sub

    Private Sub LvRecurrence_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles LvRecurrence.SelectedIndexChanged
        If LvRecurrence.SelectedItems.Count = 1 Then
            If Not (From x In bd.Recurrences Where x.ID = Convert.ToInt32(LvRecurrence.SelectedItems(0).Tag) And x.Accompagnement.HasValue Select x).Count > 0 Then
                BtnEditRec.Enabled = True
                BtnDelRec.Enabled = True
                Return
            Else
            End If
        End If
        BtnEditRec.Enabled = False
        BtnDelRec.Enabled = False
    End Sub

    Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles BtnPlacerRec.Click
        If Not horaire.Blocked Then
            For Each rec In listeRecurrence
                horaire.PlacerRecurrence(rec)
            Next
            horaire.PlacerPlages()
            horaire.init()
            If listeRecurrence.Count > 0 Then
                Modification(True, Nothing)
            End If
        End If
    End Sub

    Private Sub BtnPlacerSelRec_Click(sender As System.Object, e As System.EventArgs) Handles BtnPlacerSelRec.Click
        If LvRecurrence.SelectedItems.Count < 1 Then
            BtnPlacerSelRec.Enabled = False
            Return
        End If
        Dim selectedRecID As New List(Of Integer)
        For Each selItm As ListViewItem In LvRecurrence.SelectedItems
            selectedRecID.Add(Convert.ToInt32(selItm.Tag))
        Next
        If Not horaire.Blocked Then
            For Each rec In listeRecurrence.Where(Function(x) selectedRecID.Contains(x.ID))
                horaire.PlacerRecurrence(rec)
            Next
            horaire.PlacerPlages()
            horaire.init()
            If listeRecurrence.Count > 0 Then
                Modification(True, Nothing)
            End If
        End If
    End Sub

    Private Sub AideToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AideToolStripMenuItem.Click
        If File.Exists("Guide utilisateur.pdf") Then
            System.Diagnostics.Process.Start("Guide utilisateur.pdf")
        Else
            MsgBox("Le fichier de référence est introuvable. Vous pouvez le retrouver sur votre CD d'installation.")
        End If
    End Sub

    Private Sub TsbCurrentUser_ButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TsbCurrentUser.ButtonClick
        TsbEmploye.PerformClick()
        ListeEmploye_Naviguer((From x In bd.Employes Where x.ID = empConnecte.id Select x.ID).First, Nothing)
    End Sub

    Private Sub FrmAcceuil_FormClosing(sender As System.Object, e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If ModeEdition Or (CurPage = 1 AndAlso Not horaire.Blocked) Then
            If (CurPage = 1 AndAlso Not horaire.Blocked) Then
                MessageBox.Show("Veuillez bloquer l'horaire avant de quitter.", "Gestion CarpeDiem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Else
                MessageBox.Show("Veuillez sauvegarder avant de quitter.", "Gestion CarpeDiem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End If
            e.Cancel = True
        End If
    End Sub

End Class